#include <stdio.h>
#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_uart.h"
#include "iot_errno.h"
#include "uart_manager.h"

static UARTManager *instance = NULL;
// 延迟初始化，节省系统资源
UARTManager *get_uart_manager()
{
    if (instance == NULL)
    {
        instance = (UARTManager *)malloc(sizeof(UARTManager));
        instance->uart_idx = UART_IDX;

        IotUartAttribute uart_attr = {
            .baudRate = UART_BAUD_RATE,
            .dataBits = 8,
            .stopBits = 1,
            .parity = 0,
        };

        int32_t ret = IoTUartInit(instance->uart_idx, &uart_attr);
        if (ret != IOT_SUCCESS)
        {
            printf("UART init failed with error code: %d\n", ret);
            free(instance);
            instance = NULL;
        }
        else
        {
            printf("UART initialized successfully\n");
        }
    }
    return instance;
}

int32_t send_at_command(UARTManager *manager, const char *command, char *response, size_t response_size)
{
    if (manager == NULL || command == NULL || response == NULL)
    {
        printf("Invalid arguments\n");
        return -1;
    }

    int32_t ret = IoTUartWrite(manager->uart_idx, (unsigned char *)command, strlen(command));
    if (ret != IOT_SUCCESS)
    {
        printf("Failed to send command: %s\n", command);
        return ret;
    }

    ret = IoTUartRead(manager->uart_idx, (unsigned char *)response, response_size - 1);
    if (ret < 0)
    {
        printf("Failed to read response\n");
        return ret;
    }

    response[ret] = '\0'; // Null-terminate the response
    return IOT_SUCCESS;
}